import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Tabs, Row, Select, DatePicker, Table, Avatar } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { getOrderList, getSupplierList, getStoreList } from '@/services/order/online'
import { router } from 'umi'
import { exportsExcel } from '@/utils/utils'

const { TabPane } = Tabs

const { Option } = Select

const { RangePicker } = DatePicker

// 表头
const columns = [
  {
    title: '订单号',
    dataIndex: 'orderNo',
    key: 'orderNo',
    align: 'center'
  },
  {
    title: '下单时间',
    dataIndex: 'orderTime',
    key: 'orderTime',
    align: 'center'
  },
  {
    title: '状态',
    dataIndex: 'userOrderStatusName',
    key: 'userOrderStatusName',
    align: 'center'
  }
]

const Online = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [orderList, setOrderList] = useState([])
  const [total, setTotal] = useState(1)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [record, setRecord] = useState({})
  const [orderStartTime, setOrderStartTime] = useState('')
  const [orderEndTime, setOrderEndTime] = useState('')
  const [querySource, setQuerySource] = useState('PC')
  const [supplierList, setSupplierList] = useState([])
  const [storeList, setStoreList] = useState([])
  const [osTypeList, setOsTypeList] = useState([
    {
      id: 'Windows',
      name: 'WIN PC'
    },
    {
      id: 'IOS',
      name: 'IOS'
    },
    {
      id: 'Android',
      name: '安卓'
    },
    {
      id: 'WP',
      name: 'Window Phone'
    },
    {
      id: 'OTHER',
      name: '其他'
    }
  ])  // 操作系统
  const [platFormList, setPlatFormList] = useState([
    {
      id: 'POS',
      name: 'POS机'
    },
    {
      id: 'APP',
      name: 'APP'
    },
    {
      id: 'PC',
      name: 'PC'
    },
    {
      id: 'WECHAT_MICROSOFT',
      name: '微信小程序'
    },
    {
      id: 'WECHAT_PUB',
      name: '微信公总号'
    },
    {
      id: 'ZFB_MICROSOFT',
      name: '支付宝小程序'
    },
    {
      id: 'ZFB_PUB',
      name: '支付宝生活号'
    },
    {
      id: 'EXTERNAL_API',
      name: '外部API'
    }
  ])  // 平台来源
  const [isDistributionOrderList, setIsDistributionOrderList] = useState([
    {
      id: '0',
      name: '普通订单'
    },
    {
      id: '1',
      name: '分销订单'
    }
  ])  // 订单类型
  const [orderTypeList, setOrderTypeList] = useState([
    {
      id: 'GENERAL_ORDER',
      name: '普通买单订单'
    },
    {
      id: 'MALL_ORDER',
      name: '商城订单'
    },
    {
      id: 'RECHAR_ORDER',
      name: '充值订单'
    },
    {
      id: 'GROUP_PURCHASE_ORDER',
      name: '团购订单'
    },
    {
      id: 'PRESELL_ORDER',
      name: '预定订单'
    },
    {
      id: 'REPAST_ORDER',
      name: '餐饮订单'
    },
    {
      id: 'SUPER_MARKET_ORDER',
      name: '商超订单'
    }
  ])  // 订单类目
  const [orderPaySceneList, setOrderPaySceneList] = useState([
    {
      id: 'CASHIER',
      name: '普通收银'
    },
    {
      id: 'COUNTER_CASHIER',
      name: '单柜收银'
    },
    {
      id: 'EMPLOYER_CASHIER',
      name: '员工收银'
    },
    {
      id: 'MALL_CASHIER',
      name: '线上商城'
    },
    {
      id: 'TAB_CARD_CASHIER',
      name: '台卡收银'
    },
    {
      id: 'MEMBER_RECHARGE',
      name: '会员卡充值'
    },
    {
      id: 'PAID_GOLD_RECHARGE',
      name: '代付金充值'
    },
    {
      id: 'SMS_RECHARGE',
      name: '短信充值'
    },
    {
      id: 'LIVE_ORDER',
      name: '直播订单'
    },
    {
      id: 'ADVERTORIAL_ORDER',
      name: '软文订单'
    },
    {
      id: 'SCANQRCODE_CASHIER',
      name: '扫码点单'
    },
    {
      id: 'SECKILL_ORDER',
      name: '秒杀订单'
    },
    {
      id: 'GROUP_PURCHASE_ORDER',
      name: '拼团订单'
    }
  ])  // 支付场景
  const [payStatusList, setPayStatusList] = useState([
    {
      id: '6',
      name: '付款成功'
    },
    {
      id: '1',
      name: '待支付'
    },
    {
      id: '2',
      name: '支付中'
    },
    {
      id: '3',
      name: '支付取消'
    },
    {
      id: '4',
      name: '取消失败'
    },
    {
      id: '5',
      name: '部分付款成功'
    },
    {
      id: '10',
      name: '退款中'
    },
    {
      id: '20',
      name: '已退款'
    },
    {
      id: '30',
      name: '退款失败'
    }
  ])  // 支付状态
  const [payTypeList, setPayTypeList] = useState([
    {
      id: 'WXP',
      name: '微信支付'
    },
    {
      id: 'ALP',
      name: '支付宝支付'
    },
    {
      id: 'Bank',
      name: '银行卡支付'
    },
    {
      id: 'Cash',
      name: '现金支付'
    },
    {
      id: 'Member',
      name: '会员卡支付'
    },
    {
      id: 'Account',
      name: '余额支付'
    },
    {
      id: 'Coupon',
      name: '优惠支付'
    }
  ])  // 支付方式
  const [platOrderStatusList, setPlatOrderStatusList] = useState([
    {
      id: '1',
      name: '待支付'
    },
    {
      id: '6',
      name: '待成团'
    },
    {
      id: '2',
      name: '待发货'
    },
    {
      id: '3',
      name: '待用户收货'
    },
    {
      id: '4',
      name: '待用户自提'
    },
    {
      id: '10',
      name: '交易成功'
    },
    {
      id: '20',
      name: '交易关闭'
    },
    {
      id: '30',
      name: '已取消'
    },
    {
      id: '40',
      name: '已完成'
    }
  ])  // 订单状态

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      console.log(record)
    },
  }

  // 选择时间
  const selectData = (date, dateString) => {
    setOrderStartTime(dateString[0])
    setOrderEndTime(dateString[1])
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {
      let params = {
        pageNo: page,
        pageSize,
        querySource
      }
      getOrderLists(params)
    }
  }
  // 切换页面
  const changeTab = async value => {
    let params = {
      pageNo,
      pageSize,
      querySource: 'PC',
      platOrderStatus: value
    }
    await getOrderLists(params)
    handleReset()
  }

  useEffect(() => {
    init()
  }, [])
  const init = async () => {
    let params = {
      pageNo,
      pageSize,
      querySource
    }
    await getOrderLists(params)
    await getSupplierLists()
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)
      let params = {
        pageNo,
        pageSize,
        orderStartTime,
        orderEndTime
      }
      Object.assign(params, values)
      await getOrderLists(params)
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item label="所属商户" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('supplierId', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
                onChange={selectSupplier}
              >
                { supplierList && supplierList.map(r => <Option key={r.id} value={r.id}>{r.merchantName}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="选择门店" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('storeId', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { storeList && storeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="订单编号" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('orderNo', {})
              (<Input placeholder="请输入订单编号" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="货物单号" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('trafficNo', {})
              (<Input placeholder="请输入货物单号" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="买家信息" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('userName', {})
              (<Input placeholder="请输入买家信息" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="收货人" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('receiveName', {})
              (<Input placeholder="请输入收货人" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="商品名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('goodsName', {})
              (<Input placeholder="请输入商品名称" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="操作系统" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('osType', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { osTypeList && osTypeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="平台来源" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('platForm', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { platFormList && platFormList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="订单类型" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('isDistributionOrder', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { isDistributionOrderList && isDistributionOrderList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="订单类目" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('orderType', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { orderTypeList && orderTypeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="支付场景" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('orderPayScene', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { orderPaySceneList && orderPaySceneList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="支付状态" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('payStatus', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { payStatusList && payStatusList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="支付方式" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('payType', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { payTypeList && payTypeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="订单状态" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('platOrderStatus', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { platOrderStatusList && platOrderStatusList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="下单时间" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('date', {})
              (<RangePicker onChange={selectData} />)}
          </Form.Item>
        </Col>
      </Row>
    )
  }
  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      case 13:
        if (JSON.stringify(record) === '{}') return
        router.push({ pathname: '/order/orderDetail', query: { orderNo: record[0].orderNo, orderType: 'online' } })
        break
      // 导出excel
      case 97:
        exportsExcel({
          columns,
          data: orderList,
          title: '线上订单'
        })
        break
    }

  }
  // 获取订单列表
  const getOrderLists = async (params) => {
    let res = await getOrderList(params)
    if (res.code === '0') {
      setOrderList(res.data)
      setTotal(res.iTotalRecords)
    } else {
      alert('您点击的太快了, 请稍后尝试')
    }
  }
  // 获取商户列表
  const getSupplierLists = async () => {
    let res = await getSupplierList()
    if (res.code === '0') {
      setSupplierList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 选择商户
  const selectSupplier = async (value) => {
    await getStoreLists(value)
  }
  // 获取商铺列表
  const getStoreLists = async (supplierId) => {
    let params = {
      pageSize: 999,
      supplierId
    }
    let res = await getStoreList(params)
    if (res.code === '0') {
      setStoreList(res.data)
    } else {
      alert(res.msg)
    }
  }

  const showTables = (record) => {
    return (record.amdOrderDetailInfoList.map(r =>
      (<Row gutter={24} key={r.id}>
        <Col span={4}>{r.goodsName}</Col>
        <Col span={4}><Avatar shape="square" size="large" src={r.goodsImage} /></Col>
        <Col span={4}>价格*数量：¥{`${r.goodsPrice}×${r.goodsNums}=${r.goodsPrice*r.goodsNums}`}</Col>
        <Col span={4}>优惠：{r.goodsCoupon}</Col>
        <Col span={4}>状态：{r.payStatusName}</Col>
        <Col span={4}>收货手机号：{r.goodsAmountDue}</Col>
      </Row >))
    )
  }
  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Tabs defaultActiveKey="0" onChange={changeTab}>
        <TabPane tab="所有订单" key="0"></TabPane>
        <TabPane tab="待付款" key="1"></TabPane>
        <TabPane tab="待成团" key="6"></TabPane>
        <TabPane tab="待发货" key="2"></TabPane>
        <TabPane tab="待收货" key="3"></TabPane>
        <TabPane tab="待自提" key="4"></TabPane>
        <TabPane tab="交易成功" key="10"></TabPane>
        <TabPane tab="交易关闭" key="20"></TabPane>
        <TabPane tab="已完成" key="40"></TabPane>
        <TabPane tab="已取消" key="30"></TabPane>
      </Tabs>
      <Table
        columns={columns}
        dataSource={orderList}
        rowKey={record => record.orderNo}
        pagination={pagination}
        rowSelection={rowSelection}
        expandedRowRender={record => showTables(record)}
      />
   </PageHeaderWrapper>
  )
}

export default Form.create()(Online)
